package com.sun.audit.handle;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.sun.audit.extractor.AuditFieldExtractor;
import com.sun.audit.service.AuditLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AuditLogHandler {

    @Async
    public void handle(ApplicationContext applicationContext, Class<?> resolve, Object oldObj, Object newObj) {
        if (oldObj == null || newObj == null) {
            return;
        }
        TableInfo tableInfo = TableInfoHelper.getTableInfo(oldObj.getClass());
        Object recordId = tableInfo.getPropertyValue(newObj, tableInfo.getKeyProperty());
        log.info("获取recordId记录id对象：{}", recordId.getClass());

        // 获取用户实现的Bean
        AuditLogService auditLogService = applicationContext.getBean(AuditLogService.class);
        // 用户未实现则不记录
        if (auditLogService == null) {
            return;
        }

        AuditFieldExtractor.FieldExtractResult fieldExtractResult = AuditFieldExtractor.extractAuditFields(oldObj, newObj);

        auditLogService.saveAuditLog(
                tableInfo.getTableName(),
                recordId,
                "UPDATE",
                fieldExtractResult.getFieldNames(),
                fieldExtractResult.getFieldOldValues(),
                fieldExtractResult.getFieldNewValues()
        );
    }

    @Async
    public void handleBatch(ApplicationContext applicationContext, Class<?> resolve, List<?> oldObjs, List<?> newObjs) {
        if (oldObjs == null || oldObjs == null || oldObjs.size() != newObjs.size()) {
            return;
        }
        for (int i = 0; i < oldObjs.size(); i++) {
            handle(applicationContext, resolve, oldObjs.get(i), newObjs.get(i));
        }
    }
}
